import { UserInfoType } from '../../types/index';
import api from '../../utils/api';
import util from '../../utils/common';

Page({
  data: {
    isShow: false
  },
  onRegister () {
    // 注册
    my.navigateTo({
      url: '/pages/register/register'
    })
  },
  onIconChange() {
    this.setData({
      isShow: !this.data.isShow
    })
  },
  async onSubmit(e) {
    const { username, password } = e.detail.value;
    if (username && password) {      
      const res: UserInfoType = await api.login(e.detail.value);
      if (res?.token) {
        my.setStorageSync({key: 'token', data: res.token});
        my.setStorageSync({key: 'user', data: {userName: res.user_display_name}});
        util.showToast('登录成功', 'success', () => {
          const pages = getCurrentPages();    
          // 获取从哪个页面进入当前页面
          const prevPage = pages[pages.length - 2];  
          if (prevPage.route == 'pages/register/register'|| prevPage.route == 'pages/personal/personal') {
            my.switchTab({
              url: '/pages/mine/mine'
            })
          } else {
            // 登录完成后返回上一个页面
            my.navigateBack({
              delta: 1
            })
          }
        })
      }
    } else {
      const title = !username? '请输入用户名': '请输入密码';
      util.showToast(title);
    }
  }
});
